package com.zlm.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: 郑
 * CAS
 */
public class CasABADemo {
    static AtomicInteger atomicInteger = new AtomicInteger(1);

    public static void main(String[] args) {
        new Thread(() ->{
            try {
                System.out.println(Thread.currentThread().getName()+"====>初始值"+atomicInteger.get());
                int expectNum = atomicInteger.get();//初始值
                int newNum = expectNum + 1;
                Thread.sleep(1000);
                boolean result = atomicInteger.compareAndSet(expectNum, newNum);
                System.out.println(Thread.currentThread().getName()+"===>CAS结果："+result);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
            }
        },"主线程").start();

        new Thread(() -> {
            try {
                Thread.sleep(20);
                System.out.println(Thread.currentThread().getName()+"====>初始值"+atomicInteger.get());
                atomicInteger.incrementAndGet();
                atomicInteger.decrementAndGet();
                System.out.println(atomicInteger.compareAndSet(atomicInteger.get(), atomicInteger.get() + 1));
                System.out.println(atomicInteger.compareAndSet(atomicInteger.get(), atomicInteger.get() - 1));

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
            }

        }).start();

    }
}
